package com.ycb;


import com.ycb.entity.Order;
import com.ycb.mapper.OrderMapper;
import com.ycb.utils.MybatisUtil;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;

import java.util.concurrent.TimeUnit;

@Slf4j
public class Application {

    public static void main(String[] args) throws Exception {
        // 不进行自动提交SQL
        SqlSession sqlSession = MybatisUtil.getSqlSession(false);
        OrderMapper orderMapper =  sqlSession.getMapper(OrderMapper.class);
        // 获取连接未执行SQL不会开启事务
        log.info("inGlobalTransaction : {} branchType: {}",RootContext.inGlobalTransaction(),RootContext.getBranchType());
        try {
            for (int i = 0; i < 3; i++) {
                Order o = new Order();
                //            o.setId(1001L);
                o.setName("sharding");
                o.setAmt(10);
                orderMapper.insert(o);
                // 未提交执行SQL时开启事务
                log.info("i 【{}】 inGlobalTransaction : {} branchType: {}",i,RootContext.inGlobalTransaction(),RootContext.getBranchType());
                if (i == 3){
                    int x = 10/0;
                }
            }
            log.info(" seata commit ");
            sqlSession.commit();
        } catch (Exception e) {
            log.info(" seata rollback ");
            sqlSession.rollback();
        }
        TimeUnit.SECONDS.sleep(5L);
        log.info(" app exit ");
    }



//    private static <T extends ShardingSphereTransactionManager >ShardingSphereTransactionManager getXAShardingSphereTransactionManager(Class<T> cls){
//        ServiceLoader<ShardingSphereTransactionManager> transactionManagers = ServiceLoader.load(ShardingSphereTransactionManager.class);
//        Iterator<ShardingSphereTransactionManager> iterator = transactionManagers.iterator();
//        while (iterator.hasNext()) {
//            ShardingSphereTransactionManager next = iterator.next();
//            System.err.println(next.getClass()+" - "+next.getTransactionType());
//            if (Objects.equals(next.getClass(),cls)){
//                return next;
//            }
//        }
//        return null;
//    }


}